<script setup lang="ts">
import type { DeptDetailResult, DeptTypeOptionResult } from "@/api/types";
import type { DeptTreeExpose } from "@/components/ReCommon/src/tree/deptTree";
import { ref, watch } from "vue";
import { deptApi, deptTypeApi } from "@/api";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";
import { onlySubmitData } from "@/utils/tools";
import { useDeptForm, useDeptTree } from "../composables";
import { deptFormRules as rules } from "../utils/rules";

interface Props {
    visible?: boolean;
    mode?: "create" | "edit";
    treeRef?: DeptTreeExpose | null;
    parentDept?: DeptDetailResult | null;
}

interface Emits {
    (e: "update:visible", visible: boolean): void;
    (e: "createSuccess"): void;
    (e: "updateSuccess", data: DeptDetailResult): void;
}

const props = withDefaults(defineProps<Props>(), {
    visible: false,
    mode: "create",
    treeRef: null,
    parentDept: null,
});

const emit = defineEmits<Emits>();

const { addNodeToTree, updateNodeInTree } = useDeptTree();
const { formData, formRef, resetForm, submitLoading, handleSubmit } = useDeptForm();
const deptTypeOptions = ref<DeptTypeOptionResult[]>([]);

/** 监听弹窗显示状态 */
watch(
    () => props.visible,
    (visible) => {
        if (visible) {
            resetForm();
            if (props.mode === "create" && props.parentDept) {
                // 新增模式：设置为下级部门
                formData.parentId = props.parentDept.id;
                formData.level = props.parentDept.level + 1;
            } else if (props.mode === "edit" && props.parentDept) {
                // 编辑模式：加载当前部门信息
                loadDeptData();
            }
            getDeptTypeOptions();
        }
    },
);

/** 关闭对话框 */
function handleClose() {
    emit("update:visible", false);
}

/** 提交表单 */
function handleFormSubmit() {
    handleSubmit(
        props.mode === "edit",
        (id) => {
            if (props.mode === "create") {
                addNodeToTree(id, props.treeRef, () => {
                    emit("createSuccess");
                });
            } else if (props.mode === "edit") {
                updateNodeInTree(id, props.treeRef, (deptData) => {
                    emit("updateSuccess", deptData);
                });
            }
            handleClose();
        },
    );
}

/** 获取部门类型选项 */
async function getDeptTypeOptions() {
    const level = props.mode === "create" && props.parentDept
        ? (props.parentDept.level + 1)
        : (props.parentDept?.level || 0);
    await apiCall(
        () => deptTypeApi.listOptions(level),
        (data) => { deptTypeOptions.value = data; },
    );
}

/** 加载部门数据（编辑模式） */
function loadDeptData() {
    if (!props.parentDept?.id) return;
    apiCall(
        () => deptApi.findById(props.parentDept!.id),
        (data) => {
            Object.assign(formData, onlySubmitData(formData, data));
        },
    );
}
</script>

<template>
    <el-dialog
        :model-value="visible"
        :title="mode === 'edit' ? $t('title.editSysDept') : $t('title.createSysDept')"
        width="600px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="auto"
            label-position="right"
        >
            <el-form-item :label="$t('label.parentDept')">
                <el-input
                    :model-value="parentDept?.fullName || '无'"
                    disabled
                />
            </el-form-item>
            <el-form-item :label="$t('label.name')" prop="name">
                <el-input
                    v-model="formData.name"
                    :placeholder="$t('placeholder.inputName')"
                    clearable
                />
            </el-form-item>
            <el-form-item :label="$t('label.deptType')" prop="type">
                <el-select
                    v-model="formData.type"
                    :placeholder="$t('placeholder.select')"
                    clearable
                    style="width: 100%"
                >
                    <el-option
                        v-for="item in deptTypeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('label.phone')" prop="phone">
                <el-input
                    v-model="formData.phone"
                    :placeholder="$t('placeholder.input')"
                    clearable
                />
            </el-form-item>
            <el-form-item :label="$t('label.email')" prop="email">
                <el-input
                    v-model="formData.email"
                    :placeholder="$t('placeholder.input')"
                    clearable
                />
            </el-form-item>
            <el-form-item :label="$t('label.remark')" prop="remark">
                <el-input
                    v-model="formData.remark"
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    :rows="3"
                    :placeholder="$t('placeholder.inputRemark')"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="handleClose">
                {{ $t("button.cancel") }}
            </el-button>
            <el-button type="primary" :loading="submitLoading" @click="handleFormSubmit">
                {{ $t("button.confirm") }}
            </el-button>
        </template>
    </el-dialog>
</template>
